/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.home.dao;

import com.home.common.utils.HibernateUtil;
import com.home.mapping.ScorecardDetailsResult;
import com.home.mapping.ScorecardGroupAttributeResult;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author pnduy
 */
public class ScorecardGroupAttributeResultDao extends BaseDao{
    
    public boolean deleteByScorecardId(Integer scorecardId) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction trans = null;
        boolean returnValue = true;
        try {
            trans = session.beginTransaction();
            session.createSQLQuery("DELETE FROM scorecard_group_attribute_result WHERE scorecard_group_attribute_result.fk_scorecard = :scorecardId")
                    .addEntity(ScorecardGroupAttributeResult.class)
                    .setParameter("scorecardId", scorecardId)
                    .executeUpdate();
            trans.commit();
            
        }catch (Exception e) {
            e.printStackTrace();
            returnValue = false;
            trans.rollback();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return returnValue;
    }
    
    public List<ScorecardGroupAttributeResult> findByScorecardIds(List<Integer> scorecardIds) {
        List<ScorecardGroupAttributeResult> list = new ArrayList<>();
        if (scorecardIds.size() > 0) {
            Session session = HibernateUtil.getSessionFactory().openSession();
            try {

                Query query = session.createSQLQuery("SELECT * FROM scorecard_group_attribute_result WHERE scorecard_group_attribute_result.fk_scorecard IN(" + StringUtils.join(scorecardIds, ",") + ")")
                        .addEntity(ScorecardGroupAttributeResult.class);

                list = query.list();
                for (ScorecardGroupAttributeResult obj : list) {
                    Hibernate.initialize(obj.getAttributeGroup());
                    Hibernate.initialize(obj.getScorecard().getAgent().getTeam().getVenture());
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (session != null && session.isOpen()) {
                    session.close();
                }
            }
        }
        return list;
    }
}
